package hotel.data;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import hotel.exceptions.NoConnectionFoundException;

public abstract class ConnectionProvider 
{

	private static final String JNDI_DB_REF = "java:/comp/env/jdbc/appDb";
	private static final String JNDI_DB_REF_NOT_FOUND = "'java:/comp/env/jdbc/appDb' is not found in JNDI";

	private static DataSource ds;
	
	// Static section will be initialized only once for the whole class
    static 
    {
        try 
        {
        	// Obtain connection using the JNDI descriptor.
        	// For DataSource definition details, please refer to 
        	// META-INF/context.xml and WEB-INF/web.xml
            ConnectionProvider.ds = (DataSource) 
            		new InitialContext().lookup(ConnectionProvider.JNDI_DB_REF);
        }
        catch (NamingException e) 
        { 
            throw new ExceptionInInitializerError(
            		ConnectionProvider.JNDI_DB_REF_NOT_FOUND);
        }
    }

    // This is an ordinary static method, not a singleton approach.
    public static Connection getConnection() throws NoConnectionFoundException 
    {

    	// For direct connections refer to:
    	// class.forName("com.mysql.jdbc.Driver");
    	// DriverManager.getConnection("jdbc:mysql://"+host+":"+port +"/" + db, user, pswd);
    	
    	Connection conn = null;
    	if (ConnectionProvider.ds != null) 
    	{
    		try 
    		{
				conn = ConnectionProvider.ds.getConnection();
			}
    		catch (SQLException e) 
			{
			throw new NoConnectionFoundException(e);
			}
    	}
    	
        return conn;
    }
}
